/*
 *  Author: Honrun
 */
#include "stdio.h"
#include "stdint.h"
#include "DevicesList.h"

int8_t cListInit(ListType *ptypeNow, int64_t lValue)
{
    if(ptypeNow == NULL)
        return -1;

    ptypeNow->next  = ptypeNow->prev = ptypeNow;
    ptypeNow->value = lValue;

    return 0;
}

int8_t cListInsert(ListType *ptypeHead, ListType *ptypeNow)
{
    ListType *ptypeBase = NULL;

    if((ptypeHead == NULL) || (ptypeNow == NULL))
        return -1;

    /* 插入到最后 */
    if(ptypeNow->value >= LIST_VALUE_MAX)
    {
        return cListInsertEnd(ptypeHead, ptypeNow);
    }

    /* 找到排序插入的前一个位置 */
    for(ptypeBase = ptypeHead; ptypeBase->next->value <= ptypeNow->value; ptypeBase = ptypeBase->next);

    return cListInsertAfter(ptypeBase, ptypeNow);
}

int8_t cListInsertBefore(ListType *ptypeBase, ListType *ptypeNow)
{
    if((ptypeBase == NULL) || (ptypeNow == NULL))
        return -1;

    ptypeNow->prev        = ptypeBase->prev;
    ptypeBase->prev->next = ptypeNow;
    ptypeBase->prev       = ptypeNow;
    ptypeNow->next        = ptypeBase;

    return 0;
}

int8_t cListInsertAfter(ListType *ptypeBase, ListType *ptypeNow)
{
    if((ptypeBase == NULL) || (ptypeNow == NULL))
        return -1;

    ptypeNow->next        = ptypeBase->next;
    ptypeBase->next->prev = ptypeNow;
    ptypeBase->next       = ptypeNow;
    ptypeNow->prev        = ptypeBase;

    return 0;
}

int8_t cListInsertHead(ListType *ptypeHead, ListType *ptypeNow)
{
    return cListInsertAfter(ptypeHead, ptypeNow);
}

int8_t cListInsertEnd(ListType *ptypeHead, ListType *ptypeNow)
{
    return cListInsertBefore(ptypeHead, ptypeNow);
}

int8_t cListRemove(ListType *ptypeNow)
{
    if(ptypeNow == NULL)
        return -1;

    ptypeNow->prev->next = ptypeNow->next;
    ptypeNow->next->prev = ptypeNow->prev;

    ptypeNow->next = ptypeNow->prev = ptypeNow;

    return 0;
}
